/*
 * @Author: 悦者生存 1002783067@qq.com
 * @Date: 2023-02-28 20:33:34
 * @LastEditors: 悦者生存 1002783067@qq.com
 * @LastEditTime: 2023-11-12 11:37:55
 * @FilePath: /koa2-ts-template/src/api/system/auth/register.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import jwt from 'jsonwebtoken';
import { Models } from '../../common/typings/model';
import Config from '../../config/config.default';
import { routeConfig, z, body, ParsedArgs } from 'koa-swagger-decorator';
import { AUTH_KEY } from '../../common/swagger-extra';

interface LoginType {
  password: string;
  username: string;
}

interface RegisterType {
  password: string;
  username: string;
}

const CreateUserReq = z.object({
  username: z.string().min(1),
  password: z.string().min(1),
});

class UserController {
  @routeConfig({
    path: '/login',
    method: 'post',
    summary: 'user login',
    tags: ['USER'],
  })
  @body(CreateUserReq)
  async login(ctx: Models.Ctx, args: ParsedArgs<LoginType>) {
    const { username, password } = args.body as LoginType;
    const user = await ctx.model.User.findOne({
      where: { user_name: username },
    });
    if (!user) {
      ctx.fail('该用户不存在');
      return;
    }
    if (password !== user.password) {
      ctx.fail('密码错误');
      return;
    }
    const token = jwt.sign(
      {
        username,
      },
      Config.JWT.secret,
      { expiresIn: 60 * 60 }
    );
    ctx.success({ token }, '登录成功');
  }

  @routeConfig({
    // define your API route info using @routeConfig decorator
    method: 'get',
    path: '/users',
    summary: 'get users',
    tags: ['USER'],
    security: [{ [AUTH_KEY]: [] }],
  })
  async getUsers(ctx: Models.Ctx) {
    const users = await ctx.model.User.findAll({
      attributes: {
        exclude: ['password'],
      },
    });
    ctx.success(users);
  }

  @routeConfig({
    method: 'post',
    path: '/register',
    summary: 'create user',
    tags: ['USER'],
  })
  @body(CreateUserReq)
  async register(ctx: Models.Ctx, args: ParsedArgs<RegisterType>) {
    const { password, username } = args.body as RegisterType;
    // TODO:增加判断是否有重复用户
    const user = await ctx.model.User.findOne({
      where: { user_name: username },
    });
    if (user) {
      ctx.fail('用户重复');
      return;
    }
    // TODO:密码检测
    // 注册
    await ctx.model.User.create({ password, user_name: username });
    ctx.success('ok', '注册成功');
  }
}

export default UserController;
